/****************************************************************************************************************************
led 控制灯,大体实现逻辑
通过 esp8266 连接 wifi
通过 websocket 连接 server
编写好对应的控制灯颜色的代码
在 websocket 收到通知的时候根据预定的操作来执行
 

*****************************************************************************************************************************/

#include "defines.h"
#include <Adafruit_NeoPixel.h>
#include <WebSockets2_Generic.h>
#include <ESP8266WiFi.h>

#ifdef __AVR__

#include <avr/power.h>

#endif

#define PIN 2

#define NUM_LEDS 60

#define BRIGHTNESS 50

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);
byte neopix_gamma[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
        2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5,
        5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10,
        10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
        17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
        25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
        37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
        51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
        69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
        90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 109, 110, 112, 114,
        115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 138, 140, 142,
        144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175,
        177, 180, 182, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213,
        215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255};


using namespace websockets2_generic;
int pin = 0;
int randomcolor = 0;
WebsocketsClient client;
int status = 0;//连接状态,初始为 0 代表关闭
void onEventsCallback(WebsocketsEvent event, String data) {
    if (event == WebsocketsEvent::ConnectionOpened) {
        Serial.println("Connnection Opened");
    } else if (event == WebsocketsEvent::ConnectionClosed) {
        Serial.println("Connnection Closed");
        status = 0;//当和服务器关闭连接后设置为关闭状态
    } else if (event == WebsocketsEvent::GotPing) {
        Serial.println("Got a Ping!");
    } else if (event == WebsocketsEvent::GotPong) {
        Serial.println("Got a Pong!");
    }
}


void setup() {
    Serial.begin(115200);
    while (!Serial);

#if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
    // End of trinket special code
    strip.setBrightness(BRIGHTNESS);
    strip.begin();
    strip.show(); // Initialize all pixels to 'off'

    Serial.println("\nStarting ESP8266-RepeatingClient on " + String(ARDUINO_BOARD));
    Serial.println(WEBSOCKETS2_GENERIC_VERSION);
    // Connect to wifi
    WiFi.begin(ssid, password);//连接 wifi

    // Wait some time to connect to wifi
    for (int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
        Serial.print(".");
        delay(1000);
    }

    // Check if connected to wifi
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("No Wifi!");
        return;
    }

    Serial.print("Connected to Wifi, Connecting to WebSockets Server @");
    Serial.println(websockets_server_host);
    client.addHeader("Origin", "http://"+String(websockets_server_host));//设置来源地址,保持和服务器地址一致,防止跨域被拦截,默认是当前库的 github 地址
    //client.addHeader("Authorization", "Basic YWRtaW46YWRtaW4="); //如果使用的是原始的库,并且使用的是spring security 因为会默认添加无数据的Authorization头,可能会出现 401,需要添加账号密码 ,或者修改库的底层源码去掉默认添加的 Authorization 空头,内容是Basic 账号:密码的base64,可以通过修改库的底层源码去掉默认空的认证信息
    int var;
    // run callback when messages are received
    client.onMessage([&](WebsocketsMessage message) {
        Serial.print("Got Message: ");
        String command = message.data(); //获取到服务端发来的数据
        Serial.print(command);
        Serial.print("\n");
//        if (command == "0") { //设置为默认颜色
//            randomcolor = 0;
//        }
//        if (command == "1") {//
//            randomcolor = 1;
//        }
  
        if (command == "2") {//如果服务器发送的是 1 则设置状态为 1 高电平
           if( randomcolor ==3){
             randomcolor = 0;
            }else{
               randomcolor++;
              }
        }
      
    });

    // run callback when events are occuring
    client.onEvent(onEventsCallback); //设置websocket 的回调
}


void sendMessage(void) {
// try to connect to Websockets server
    //连接方式 1
    bool connected = client.connect(websockets_server_host, websockets_server_port,
                                    "/colorcommand/1234567890"); //和服务器连接,主机和地址在 defines 文件中声明
    //连接方式 2
    //bool connected =  client.connect("ws://"+String(websockets_server_host)+":"+String(websockets_server_port)+"/websocket/1234567890"); //比如ws://192.168.3.2/websocket/aaaa

    if (connected) {
        Serial.println("Connected!");
        status = 1; //连接后修改状态为已连接
        String WS_msg = String("Hello to Server from ") + BOARD_NAME;
        client.send(WS_msg); //随便发送了一条消息
    } else {
        Serial.println("Not Connected!");
    }
}

void checkToSendMessage() {
#define REPEAT_INTERVAL    20000L

    static unsigned long checkstatus_timeout = 0;

    // Send WebSockets message every REPEAT_INTERVAL (10) seconds.
    //重连检查,每 10 秒检查一下,如果是关闭状态则重新连接
    if (((millis() > checkstatus_timeout) || (checkstatus_timeout == 0)) && status == 0) {
        sendMessage();
        checkstatus_timeout = millis() + REPEAT_INTERVAL;
    } else if (((millis() > checkstatus_timeout) || (checkstatus_timeout == 0)) &&
               status == 1) {//如果是连接状态,则每 20 秒发送一条 ping 消息
        client.send("ping");
        checkstatus_timeout = millis() + REPEAT_INTERVAL;
    }
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  if(randomcolor!=0){
    return;
  }
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
} 

void pulseWhite(uint8_t wait) {
   if(randomcolor!=2){
    return;
  }
  for(int j = 0; j < 256 ; j++){
      for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(0,0,0, neopix_gamma[j] ) );
        }
        delay(wait);
        strip.show();
      }

  for(int j = 255; j >= 0 ; j--){
      for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(0,0,0, neopix_gamma[j] ) );
        }
        delay(wait);
        strip.show();
      }
}


void rainbowFade2White(uint8_t wait, int rainbowLoops, int whiteLoops) {
   if(randomcolor!=3){
    return;
  }
  float fadeMax = 100.0;
  int fadeVal = 0;
  uint32_t wheelVal;
  int redVal, greenVal, blueVal;

  for(int k = 0 ; k < rainbowLoops ; k ++){
    
    for(int j=0; j<256; j++) { // 5 cycles of all colors on wheel

      for(int i=0; i< strip.numPixels(); i++) {

        wheelVal = Wheel(((i * 256 / strip.numPixels()) + j) & 255);

        redVal = red(wheelVal) * float(fadeVal/fadeMax);
        greenVal = green(wheelVal) * float(fadeVal/fadeMax);
        blueVal = blue(wheelVal) * float(fadeVal/fadeMax);

        strip.setPixelColor( i, strip.Color( redVal, greenVal, blueVal ) );

      }

      //First loop, fade in!
      if(k == 0 && fadeVal < fadeMax-1) {
          fadeVal++;
      }

      //Last loop, fade out!
      else if(k == rainbowLoops - 1 && j > 255 - fadeMax ){
          fadeVal--;
      }

        strip.show();
        delay(wait);
    }
  
  }



  delay(500);


  for(int k = 0 ; k < whiteLoops ; k ++){

    for(int j = 0; j < 256 ; j++){

        for(uint16_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, strip.Color(0,0,0, neopix_gamma[j] ) );
          }
          strip.show();
        }

        delay(2000);
    for(int j = 255; j >= 0 ; j--){

        for(uint16_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, strip.Color(0,0,0, neopix_gamma[j] ) );
          }
          strip.show();
        }
  }

  delay(500);


}

void whiteOverRainbow(uint8_t wait, uint8_t whiteSpeed, uint8_t whiteLength ) {
   if(randomcolor!=1){
    return;
  }
  if(whiteLength >= strip.numPixels()) whiteLength = strip.numPixels() - 1;

  int head = whiteLength - 1;
  int tail = 0;

  int loops = 3;
  int loopNum = 0;

  static unsigned long lastTime = 0;


  while(true){
    for(int j=0; j<256; j++) {
      for(uint16_t i=0; i<strip.numPixels(); i++) {
        if((i >= tail && i <= head) || (tail > head && i >= tail) || (tail > head && i <= head) ){
          strip.setPixelColor(i, strip.Color(0,0,0, 255 ) );
        }
        else{
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        
      }

      if(millis() - lastTime > whiteSpeed) {
        head++;
        tail++;
        if(head == strip.numPixels()){
          loopNum++;
        }
        lastTime = millis();
      }

      if(loopNum == loops) return;
    
      head%=strip.numPixels();
      tail%=strip.numPixels();
        strip.show();
        delay(wait);
    }
  }
  
}
void fullWhite() {
  
    for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(0,0,0, 255 ) );
    }
      strip.show();
}


// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256 * 5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3,0);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3,0);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0,0);
}

uint8_t red(uint32_t c) {
  return (c >> 16);
}
uint8_t green(uint32_t c) {
  return (c >> 8);
}
uint8_t blue(uint32_t c) {
  return (c);
}

//初始循环
void loop() {

    checkToSendMessage();

    // let the websockets client check for incoming messages
    if (client.available()) {
        client.poll();
    }

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White

  whiteOverRainbow(20,75,5);  

  pulseWhite(5); 

  // fullWhite();
  // delay(2000);

  rainbowFade2White(3,3,1);
}
